from bs4 import BeautifulSoup
html = '''
<html><head><title>The Dormouse's story</title></head>
<body>
'''
# 嵌套选择
soup = BeautifulSoup(html,'lxml')
print(soup)
print(soup.head)
print(soup.head.title)
print(type(soup.head.title))
print(soup.head.title.string)
# 关联选择
html = '''
<html>
<head>
<title>The Dormouse's story</title>
</head>
<body>
<p class = "story">
    Once upon a time there were three little sisters;and their names were
    <a href = "http://example.com/elsie" class="sister" id ="link1>
<span>Elsie</span>
</a>
<a href = "http://example.com/lacie" class="sister" id ="link2>Lacie</a>
and
<a href = "http://example.com/tillie" class="sister" id ="link3>Tillie</a>;
and they lived at the bottom of a well.
</p>
<p class="story">...</p>
'''
# 子节点和子孙节点,选取节点元素之后，如果想要获取它的直接子节点，可以用contents
soup = BeautifulSoup(html,'lxml')
print(soup.p.contents)#返回生成器
print(soup.p.children)
for i ,child in enumerate(soup.p.children):
    print(i,child)
# 得到所有子孙节点用descendants属性
print(soup.p.descendants)
for i,child in enumerate(soup.p.descendants):
    print(i,child)
print('+++++++++++++++++++++++++')
html = '''
<html>
<head>
<title>The Dormouse's story</title>
</head>
<body>
<p class = "story">
Once upon a time there were three little sisters;and their names were
<a href = "http://example.com/elsie" class="sister" id ="link1>
<span>Elsie</span>
</a>
</p>
<p class="story">...</p>
'''
# 父节点和祖先节点
soup = BeautifulSoup(html,'lxml')
print(soup.a.parent)#父节点
print(soup.a.parents)#祖先节点
print(type(soup.a.parents))
print('+++++++++++++++++++++++++++')
print(list(enumerate(soup.a.parents)))

html = '''
<html>
<body>
<p class = "story">
        Once upon a time there were three little sisters;and their names were
<a href = "http://example.com/elsie" class="sister" id ="link1>
<span>Elsie</span>
</a>
        Hello
<a href = "http://example.com/lacie" class="sister" id ="link2>Lacie</a>
        and
<a href = "http://example.com/tillie" class="sister" id ="link3>Tillie</a>;
        and they lived at the bottom of a well.
</p>
'''
soup = BeautifulSoup(html,'lxml')
print('Next Sibling',soup.a.next_sibling)#上一个兄弟元素
print('Prev Sibling',soup.a.previous_sibling)#下一个兄弟元素
print('Next Sibling',list(enumerate(soup.a.next_sibling)))
print('Prev Sibling',list(enumerate(soup.a.previous_sibling)))

#提取信息
html = '''
<html>
<body>
<p class = "story">
        Once upon a time there were three little sisters;and their names were
<a href = "http://example.com/elsie" class="sister" id ="link1>Bob</a><a href = "http://example.com/lacie" class="sister" id ="link2>Lacie</a>
</p>
'''
soup = BeautifulSoup(html,'lxml')
print("Next Sibling")
print(type(soup.a.next_sibling))
print(soup.a.next_sibling)
print(soup.a.next_sibling.string)
print("Parent:")
print(type(soup.a.parents))
print(soup.a.parents)
print(list(soup.a.parents)[0])
print(list(soup.a.parents)[0].attrs['class'])